package com.cmcc.groupcontacts.firewall.business;

import java.util.ArrayList;

import android.database.Cursor;
import android.provider.CallLog;
import android.provider.CallLog.Calls;

import com.cmcc.groupcontacts.common.Const;
import com.cmcc.groupcontacts.firewall.dao.FilterListDAO;
import com.cmcc.groupcontacts.firewall.dao.model.CallInfoVO;
import com.cmcc.groupcontacts.firewall.dao.model.FilterListVO;
import com.cmcc.groupcontacts.util.ExceptionHandler;
import com.cmcc.groupcontacts.util.StringUtil;

/**
 * 黑白名单业务处理类
 * 
 * @author 
 * 
 */
/**
 * @author jerycn
 *
 */
public class FilterListBusiness extends BaseBusiness {
	private FilterListDAO filterListDAO;

	public FilterListBusiness() {
		super();

		filterListDAO = new FilterListDAO();
	}

	/**
	 * 获取所有黑白名单
	 * 
	 * @return
	 */
	public ArrayList<FilterListVO> getFilterList(boolean isBlackList) {
		String where;
		if (isBlackList) {
			where = FilterListVO.MetaData.TYPE + " = " + FilterListVO.TYPE_BLACK + " OR "+FilterListVO.MetaData.TYPE + " = " + FilterListVO.TYPE_BLACK_AREA + " OR "+FilterListVO.MetaData.TYPE + " = " + FilterListVO.TYPE_BLACK_AREA_CODE;
		} else {
			where = FilterListVO.MetaData.TYPE + " = " + FilterListVO.TYPE_WHITE;
		}
		return filterListDAO.query(false, FilterListVO.MetaData.ALL_COLS, where, null, null, null, null, null);
	}
	
	public ArrayList<FilterListVO> getFilterList(int type) {
		String where;
		where = FilterListVO.MetaData.TYPE + " = " + type;
		return filterListDAO.query(false, FilterListVO.MetaData.ALL_COLS, where, null, null, null, null, null);
	}

	/**
	 * 获取黑白名单
	 * 
	 * @param number
	 * @param type
	 * @return
	 */
	public FilterListVO get(String number, int type) {
		String where;
		if (type == FilterListVO.TYPE_ALL) {
			where = StringUtil.format("PHONE_NUMBERS_EQUAL({0},'{1}',0)", FilterListVO.MetaData.NUMBER, number);
		} else if(type == FilterListVO.TYPE_BLACK || type == FilterListVO.TYPE_WHITE){
			where = StringUtil.format("PHONE_NUMBERS_EQUAL({0},'{1}',0) AND {2}={3}", FilterListVO.MetaData.NUMBER, number, FilterListVO.MetaData.TYPE, type);
		}else{
			where = StringUtil.format("{0}=='{1}' AND {2}={3}", FilterListVO.MetaData.NUMBER, number, FilterListVO.MetaData.TYPE, type);
		}
		ArrayList<FilterListVO> filters = filterListDAO.query(false, FilterListVO.MetaData.ALL_COLS, where, null, null, null, null, null);
		return (filters == null || filters.size() == 0) ? null : filters.get(0);
	}

	/**
	 * 获取通话记录数据
	 * 
	 * @return
	 */
	public ArrayList<CallInfoVO> getCallLogList() {
		Cursor cursor = null;
		try {
			if (Const.IS_SDK_VERSION_LESS_THAN_ANDROID4) {
				String[] projection = new String[] { Calls.NUMBER, Calls.CACHED_NAME, "max(date) as " + Calls.DATE,
						"case when length(number)>7 then substr(number,length(number)-6) else number end as match_number" };
				String where = "1=1) group by(match_number";
				cursor = cr.query(CallLog.Calls.CONTENT_URI, projection, where, null, CallLog.Calls.DEFAULT_SORT_ORDER);
				if (cursor != null) {
					ArrayList<CallInfoVO> callLogs = new ArrayList<CallInfoVO>();
					for (int i = 0; i < cursor.getCount(); i++) {
						cursor.moveToPosition(i);
						CallInfoVO callLog = new CallInfoVO();
						callLog.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
						callLog.setName(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
						callLog.setDate(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
						if (callLog != null) {
							callLogs.add(callLog);
						}
					}
					return callLogs;
				} else {
					return null;
				}
			} else {
				// TODO: [BUG]Android4.0的通话记录数据获取
				String[] projection = new String[] { Calls.NUMBER, Calls.CACHED_NAME, Calls.DATE };
				cursor = cr.query(CallLog.Calls.CONTENT_URI, projection, null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
				if (cursor != null) {
					ArrayList<CallInfoVO> callLogs = new ArrayList<CallInfoVO>();
					for (int i = 0; i < cursor.getCount(); i++) {
						cursor.moveToPosition(i);
						// 借助CallListVO来存放通话记录数据
						CallInfoVO callLog = new CallInfoVO();
						callLog.setNumber(cursor.getString(cursor.getColumnIndex(CallLog.Calls.NUMBER)));
						callLog.setName(cursor.getString(cursor.getColumnIndex(CallLog.Calls.CACHED_NAME)));
						callLog.setDate(cursor.getLong(cursor.getColumnIndex(CallLog.Calls.DATE)));
						if (callLog != null) {
							callLogs.add(callLog);
						}
					}
					return callLogs;
				} else {
					return null;
				}
			}
		} finally {
			if (cursor != null && !cursor.isClosed()) {
				cursor.close();
			}
		}
	}

	/**
	 * 将电话信息插入黑白名单（不存在则新增，已存在则更新）
	 * 
	 * @param callInfo
	 * @param isBlackList
	 * @return
	 */
	public long insert(CallInfoVO callInfo, boolean isBlackList) {
		try {
			// 如果数据库中不存在则新增，已存在则更新
			String number = callInfo.getNumber();
			FilterListVO filter = get(number, FilterListVO.TYPE_ALL);
			if (filter == null) {
				// 新增
				filter = new FilterListVO();
				setFilter(filter, callInfo, isBlackList);
				return filterListDAO.add(filter);
			} else {
				// 更新
				filter.setType(isBlackList ? FilterListVO.TYPE_BLACK : FilterListVO.TYPE_WHITE);
				setFilter(filter, callInfo, isBlackList);
				return update(filter);
			}
		} catch (Exception e) {
			ExceptionHandler.handleAcceptable(e, "插入到黑白名单时出错");
			return -1;
		}
	}

	public long insert(FilterListVO vo){
		try {
			// 如果数据库中不存在则新增，已存在则更新
			FilterListVO filter = get(vo.getNumber(), vo.getType());
			if (filter == null) {
				// 新增
				return filterListDAO.add(vo);
			} else {
				// 更新
				vo.setId(filter.getId());
				return update(vo);
			}
		} catch (Exception e) {
			ExceptionHandler.handleAcceptable(e, "插入到黑白名单时出错");
			return -1;
		}
	}
	/**
	 * 将黑白名单更新到数据库中
	 * 
	 * @param filter
	 * @return
	 */
	public long update(FilterListVO filter) {
		try {
			return filterListDAO.update(filter, FilterListVO.MetaData.ID + "=" + filter.getId(), null);
		} catch (Exception e) {
			ExceptionHandler.handleAcceptable(e, "更新到黑白名单时出错");
			return -1;
		}
	}

	/*
	 * 设置黑白名单数据模型值
	 */
	private void setFilter(FilterListVO filter, CallInfoVO callInfo, boolean isBlackList) {
		filter.setNumber(callInfo.getNumber());
		filter.setName(callInfo.getName());
		if (isBlackList) {
			filter.setType(FilterListVO.TYPE_BLACK);
		} else {
			filter.setType(FilterListVO.TYPE_WHITE);
		}
		filter.setCallState(FilterListVO.STATE_BLOCK);
		filter.setSmsState(FilterListVO.STATE_BLOCK);
	}

	/**
	 * 删除指定的黑白名单
	 * 
	 * @param id
	 * @return
	 */
	public long delete(Integer id) {
		return filterListDAO.del(FilterListVO.MetaData.ID + "=" + id, null);
	}
	
	/**
	 * 取得地区名称数组
	 * @return
	 */
	public String[] loadAreaNames(){
		return new String[]{"北京","上海","天津","重庆"};
	}
	
	/**
	 * 根据号码取得归属地地区名称
	 * @param number
	 * @return
	 */
	public String getAreaNameByNumber(String number){
		return "重庆";
	}
}
